package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;



@Service
public class SetmealServiceImpl implements SetmealService {


    @Autowired
    private SetmealMapper SetmealMapper;


    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //分页查询
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //进行查询
        Page<Setmeal> p= SetmealMapper.findPage(queryPageBean);
        //封装返回结果
        return  new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    public Setmeal findById(Integer id) {
        return SetmealMapper.findById(id);
    }

    /**
     * 增加套餐
     * @param checkGroupIds
     * @param setmeal
     */
    @Override
    public void add(List<Integer> checkGroupIds, Setmeal setmeal) {
        //增加套餐
        SetmealMapper.add(setmeal);
        //添加套餐和检查组的关联关系
        if(checkGroupIds!=null&&checkGroupIds.size()>0){
            for (Integer checkGroupId : checkGroupIds) {
                SetmealMapper.addCheckGroupAndSetmeal(setmeal.getId(),checkGroupId);
            }
        }
    }

    /**
     * 编辑套餐
     * @param checkGroupIds
     * @param setmeal
     */
    @Transactional
    @Override
    public void edit(List<Integer> checkGroupIds, Setmeal setmeal) {
        //修改套餐
        SetmealMapper.update(setmeal);
        //修改套餐和检查组的关联关系
        if(checkGroupIds!=null&&checkGroupIds.size()>0){
            //删除套餐和检查组的关联关系
            SetmealMapper.deleteCheckGroupAndSetmeal(setmeal.getId());
            //添加套餐和检查组的关联关系
            for (Integer checkGroupId : checkGroupIds) {
                SetmealMapper.addCheckGroupAndSetmeal(setmeal.getId(),checkGroupId);
            }
        }
    }

    /**
     * 删除套餐
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //删除套餐和检查组的关联关系
        SetmealMapper.deleteCheckGroupAndSetmeal(id);
        //删除套餐
        SetmealMapper.deleteById(id);
    }

}